<?php
declare (strict_types=1);

namespace app\course\logic\live;

use app\admin\logic\system\Config as SystemConfig;
use app\common\exception\LogicException;
use app\course\logic\base\Course;
use GuzzleHttp\Client;

/**
 * CC云课堂接口类
 * Author 亓官雨树<lucky.max@foxmail.com>
 * Date：   2021-10-27
 */
class BokeKT
{
    /**
     * 接口uri
     *
     * @var string
     */
    protected $uri = 'https://ccapi.csslcloud.net/api/';

    /**
     * User ID
     *
     * @var string
     */
    protected $userid = '';

    /**
     * APIKey
     *
     * @var string
     */
    protected $apikey = '';

    /**
     * @var int
     */
    protected $mhmId = 0;

    /**
     * 构造函数
     */
    public function __construct(int $courseId = 0)
    {
        $this->mhmId  = $courseId ? app(Course::class)->where('id', $courseId)->value('mhm_id') : request()->mhm_id;
        $config       = $this->get_cclive_config();
        $this->userid = $config['UserID'] ?? '';
        $this->apikey = $config['classAPIKey'] ?? '';
    }

    /**
     * 获取创建人CC账号ID
     */
    public function get_user_id()
    {
        return $this->userid;
    }

    public function clientCC($param)
    {
        $uri = $param['uri'];
        unset($param['uri']);
        ksort($param);
        $str = '';
        foreach ($param as $k => $v) {
            $str .= $k . '=' . urlencode(strval($v)) . '&';
        }
        $str      .= 'time=' . time();
        $md5      = md5($str . '&salt=' . $this->apikey);
        $str      .= '&hash=' . $md5;
        $uri      .= '?' . $str;
        $client   = new Client();
        $res      = $client->get($uri);
        $response = $res->getBody()->getContents();

        return json_decode($response);
    }

    /**
     * 获取小班课全景回放链接
     */
    public function getFullRecordUrl($param)
    {
        $param['uri']        = 'https://ccapi.csslcloud.net/openapi/recorder/replay_info';
        $param['account_id'] = $this->userid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') {
            return $response;
        } else {
            throw new LogicException($response->errorMsg);
        }
    }

    /**
     * 获取自动登录链接
     */
    public function getAutoLoginUri($param)
    {
        $param['uri']    = $this->uri . 'v1/room/auto_link';
        $param['userid'] = $this->userid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') {
            return $response->data;
        } else {
            throw new LogicException($response->errorMsg);
        }
    }

    /**
     * 创建直播间
     */
    public function createRoom($param)
    {
        // 接口验证地址
        $pass_url = request()->domain() . '/course/cclive/room/entry';
        // 参数
        $param['uri']               = $this->uri . 'room/create';
        $param['userid']            = $this->userid;
        $param['room_type']         = '2';
        $param['talker_authtype']   = '0';
        $param['talker_pass']       = $pass_url;
        $param['publisherpass']     = $param['publisherpass'] ?? '123456';
        $param['assist_pass']       = $param['assist_pass'] ?? '123456';
        $param['audience_authtype'] = '0';
        $param['audience_pass']     = $pass_url;
        $param['templatetype']      = 32;
        $param['layout_mode']       = 0;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return $response->data->roomid;

        throw new LogicException($response->errorMsg);
    }

    /**
     * 直播间信息
     */
    public function roomInfo($roomid)
    {
        $param['uri']    = $this->uri . 'room/search';
        $param['userid'] = $this->userid;
        $param['roomid'] = $roomid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return $response->room;

        throw new LogicException($response->reason);
    }

    /**
     * 回放信息
     */
    public function replayInfo($recordid)
    {
        $param['uri']      = $this->uri . 'v2/record/search';
        $param['userid']   = $this->userid;
        $param['recordid'] = $recordid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return $response->record;

        throw new LogicException($response->reason);
    }

    /**
     * 合并回放
     */
    public function mergeReplay($param): array
    {
        $param['uri']    = $this->uri . 'live/merge';
        $param['userid'] = $this->userid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return ['recordid' => $response->recordid, 'liveid' => $response->liveid];

        throw new LogicException($response->reason);
    }

    /**
     * 编辑回放
     */
    public function upReplay($param): bool
    {
        $param['uri']    = $this->uri . 'record/edit';
        $param['userid'] = $this->userid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return true;

        throw new LogicException($response->reason);
    }

    /**
     * 获取后台配置
     */
    public function get_cclive_config()
    {
        $config = SystemConfig::get('course.live.config.cclive', [], $this->mhmId);
        if (empty($config)) throw new LogicException('服务暂不可用');

        return $config;
    }

    /**
     * 进出记录
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/19
     *
     * @param $roomId
     * @param $liveId
     * @return mixed
     */
    public function record($roomId, $liveId)
    {
        $param = [
            'uri'    => 'https://ccapi.csslcloud.net/collect/live/user/record/',
            'userid' => $this->userid,
            'liveid' => $liveId,
            'roomid' => $roomId
        ];

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return $response;

        throw new LogicException($response->reason);
    }

    /**
     * 管理端获取自动登录链接
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/01/31
     *
     * @param $roomid
     * @return string
     */
    public function getLoginLink($roomid)
    {
        $param['uri']    = $this->uri . 'room/auto_link';
        $param['userid'] = $this->userid;
        $param['roomid'] = $roomid;

        $response = $this->clientCC($param);

        if ($response->result == 'OK') return $response->data->presenter_url . '&username=' . request()->user->user_name . '&password=123456&autoLogin=true';

        throw new LogicException($response->errorMsg);

    }

}
